package com.cgnpc.scp.hse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.hse.mybatis.entity.HseMeetingUser;
import com.cgnpc.scp.hse.mybatis.mapper.client.HseMeetingUserMapper;
import com.cgnpc.scp.hse.service.IHseMeetingUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@Service
public class HseMeetingUserServiceImpl implements IHseMeetingUserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HseMeetingUserServiceImpl.class);

    @Autowired
    private HseMeetingUserMapper hseMeetingUserMapper;

    /**
     * 创建查询Example
     *
     * @param reqEntity reqEntity
     * @param <T>       T
     * @return Example
     */
    private <T extends HseMeetingUser> QueryWrapper<T> createQueryExample(T reqEntity) {
        // mybatis查询方式
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();

        // 设置排序字段
        queryWrapper.orderByAsc("order_index");

        // 设置查询条件

        // 会议ID
        queryWrapper.eq("meeting_info_id", reqEntity.getMeetingInfoId());

        return queryWrapper;
    }

    @Override
    public <T extends HseMeetingUser> MyPageResult<T> loadByPaging(T reqEntity) {
        // begin 分页查询
        // 第几页
        int pageNum = reqEntity.getPageNum();
        // 每页的数量
        int pageSize = reqEntity.getPageSize();

        // 创建Page对象
        IPage<HseMeetingUser> queryPage = new Page<>();
        queryPage.setCurrent(pageNum);
        queryPage.setSize(pageSize);

        // 创建queryExample
        QueryWrapper<HseMeetingUser> queryWrapper = createQueryExample(reqEntity);

        IPage<HseMeetingUser> pageResult = hseMeetingUserMapper.selectPage(queryPage, queryWrapper);

        // 创建分页结果集对象
        MyPageResult<HseMeetingUser> myPageResult = MyPageResultUtil.createMyPageResultPlus(pageResult);
        // end 分页查询

        return (MyPageResult<T>) myPageResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseMeetingUser> AjaxResult saveOrUpdate(UserInfo loginUserInfo, Locale reqLocale, String meetingInfoId, List<T> reqEntityList) {
        final String logInfo = "[HseMeetingUser_saveOrUpdate_UUID_" + UUID.randomUUID() + "]";
        AjaxResult ajaxResult = null;

        try {
            LOGGER.info("{}printInfo;meetingInfoId:{};"
                    , logInfo
                    , meetingInfoId
            );

            if (StringUtil.isNullOrSpace(meetingInfoId)) {
                LOGGER.info("meetingInfoId is null or space");
                throw new ScpException("meetingInfoId is null or space");
            }

            Date nowDate = new Date();

            // begin 获取登录用户的信息
            String loginUserInfoUserId = loginUserInfo.getUserId();
            String loginUserInfoUserName = loginUserInfo.getUserName();
            // end 获取登录用户的信息

            HseMeetingUser usedEntity = null;
            int saveRows = 0;
            int updateRows = 0;

            // String reqId = null;
            Integer reqEntityMeetingUserType = null;
            String reqEntityMeetingUser = null;
            String reqEntityMeetingUserName = null;
            Integer reqEntityMeetingSignIn = null;
            Date reqEntityMeetingSignInTime = null;
            Integer reqEntitySmsNotice = null;
            Integer reqEntitySmsSendStatus = null;

            long userCountRows = 0;

            List<String> usedUserWithUserType1List = new ArrayList<>();
            List<String> usedUserWithUserType2List = new ArrayList<>();
            List<String> usedUserWithUserType3List = new ArrayList<>();

            for (HseMeetingUser reqEntity : reqEntityList) {
                //    "meetingUser": "参会人员工号001",
                //    "meetingUser---desc": "参会人员工号，一般为userCode，根据该值更新；",
                //    "meetingUserName": "参会人员姓名王笑笑",
                //    "meetingUserName--desc": "参会人员姓名"

                // reqId = reqEntity.getId();
                // meeting_user_type 参会人员类型；值1为与会人员；
                reqEntityMeetingUserType = reqEntity.getMeetingUserType();
                reqEntityMeetingUser = reqEntity.getMeetingUser();
                reqEntityMeetingUserName = reqEntity.getMeetingUserName();
                // meeting_sign_in 签到状态：值0未签到;1已签到；
                reqEntityMeetingSignIn = reqEntity.getMeetingSignIn();
                reqEntityMeetingSignInTime = reqEntity.getMeetingSignInTime();
                reqEntitySmsNotice = reqEntity.getSmsNotice();
                reqEntitySmsSendStatus = reqEntity.getSmsSendStatus();

                reqEntityMeetingUserType = reqEntityMeetingUserType != null ? reqEntityMeetingUserType : HseMeetingUser.MEETINGUSERTYPE_1_ATTENDEES;
                reqEntityMeetingSignIn = reqEntityMeetingSignIn != null ? reqEntityMeetingSignIn : HseMeetingUser.MEETINGSIGNIN_0;

                if (reqEntityMeetingUserType == null) {
                    // 什么都不做
                } else if (reqEntityMeetingUserType == HseMeetingUser.MEETINGUSERTYPE_1_ATTENDEES) {
                    usedUserWithUserType1List.add(reqEntityMeetingUser);
                } else if (reqEntityMeetingUserType == HseMeetingUser.MEETINGUSERTYPE_2_LEADING) {
                    usedUserWithUserType2List.add(reqEntityMeetingUser);
                } else if (reqEntityMeetingUserType == HseMeetingUser.MEETINGUSERTYPE_3_TEAM_SAFETY) {
                    usedUserWithUserType3List.add(reqEntityMeetingUser);
                }

                // begin 查询数据库是否存在该用户

                QueryWrapper<HseMeetingUser> queryWrapper = new QueryWrapper<>();

                queryWrapper.eq("meeting_info_id", meetingInfoId);
                queryWrapper.eq("meeting_user_type", reqEntityMeetingUserType);
                queryWrapper.eq("meeting_user", reqEntityMeetingUser);

                userCountRows = hseMeetingUserMapper.selectCount(queryWrapper);


                // end 查询数据库是否存在该用户

                if (userCountRows <= 0) {
                    // 保存

                    usedEntity = new HseMeetingUser();
                    // 设置主键
                    usedEntity.setId(IDHelper.uuidNew());
                    // meeting_info_id 会议ID
                    usedEntity.setMeetingInfoId(meetingInfoId);
                    // meeting_user_type 参会人员类型；值1为与会人员；
                    usedEntity.setMeetingUserType(reqEntityMeetingUserType);
                    // meeting_user 参会人员工号
                    usedEntity.setMeetingUser(reqEntityMeetingUser);
                    // meeting_user_name 参会人员姓名，例如：[P206992]张平
                    usedEntity.setMeetingUserName(reqEntityMeetingUserName);
                    // meeting_sign_in 签到状态：值0未签到;1已签到；
                    usedEntity.setMeetingSignIn(reqEntityMeetingSignIn);
                    // meeting_sign_in_time 签到时间
                    usedEntity.setMeetingSignInTime(reqEntityMeetingSignInTime);
                    // sms_notice 是否短信通知；值0不通知；1通知；默认1；
                    usedEntity.setSmsNotice(reqEntitySmsNotice);
                    // sms_send_status 短信发送状态；0未发送；1已经发送；
                    // sms_send_status 新增会议时短信发送状态为未发送；该接口不修改短信发送状态；
                    usedEntity.setSmsSendStatus(HseMeetingUser.SMSSENDSTATUS_0);

                    // begin 设置公共字段
                    // create_time 创建时间
                    usedEntity.setCreateTime(nowDate);
                    // create_user 创建人员工号
                    usedEntity.setCreateUser(loginUserInfoUserId);
                    // create_user_name 创建人姓名，例如：[P206992]张平
                    usedEntity.setCreateUserName(loginUserInfoUserName);
                    // last_update_time 更新时间
                    usedEntity.setLastUpdateTime(nowDate);
                    // last_update_user 更新人员工号
                    usedEntity.setLastUpdateUser(loginUserInfoUserId);
                    // last_update_user_name 更新人姓名，例如：[P206992]张平
                    usedEntity.setLastUpdateUserName(loginUserInfoUserName);
                    // end 设置公共字段

                    saveRows += hseMeetingUserMapper.insert(usedEntity);
                } else {
                    // 修改

                    usedEntity = new HseMeetingUser();
                    // 设置主键
                    // usedEntity.setId(reqId); // id不更新
                    // meeting_info_id 会议ID
                    // usedEntity.setMeetingInfoId(meetingInfoId); // meetingInfoId不更新
                    // meeting_user_type 参会人员类型；值1为与会人员；
                    usedEntity.setMeetingUserType(reqEntityMeetingUserType);
                    // meeting_user 参会人员工号
                    usedEntity.setMeetingUser(reqEntityMeetingUser);
                    // meeting_user_name 参会人员姓名，例如：[P206992]张平
                    usedEntity.setMeetingUserName(reqEntityMeetingUserName);
                    // meeting_sign_in 签到状态：值0未签到;1已签到；
                    usedEntity.setMeetingSignIn(reqEntityMeetingSignIn);
                    // meeting_sign_in_time 签到时间
                    usedEntity.setMeetingSignInTime(reqEntityMeetingSignInTime);
                    // sms_notice 是否短信通知；值0不通知；1通知；默认1；
                    usedEntity.setSmsNotice(reqEntitySmsNotice);
                    // sms_send_status 短信发送状态；0未发送；1已经发送；
                    // sms_send_status 新增会议时短信发送状态为未发送；该接口不修改短信发送状态；
                    // usedEntity.setSmsSendStatus(); // 该接口不修改短信发送状态

                    // begin 设置公共字段
                    // create_time 创建时间
                    // usedEntity.setCreateTime(nowDate);
                    // create_user 创建人员工号
                    // usedEntity.setCreateUser(loginUserInfoUserId);
                    // create_user_name 创建人姓名，例如：[P206992]张平
                    // usedEntity.setCreateUserName(loginUserInfoUserName);
                    // last_update_time 更新时间
                    usedEntity.setLastUpdateTime(nowDate);
                    // last_update_user 更新人员工号
                    usedEntity.setLastUpdateUser(loginUserInfoUserId);
                    // last_update_user_name 更新人姓名，例如：[P206992]张平
                    usedEntity.setLastUpdateUserName(loginUserInfoUserName);
                    // end 设置公共字段

                    updateRows += hseMeetingUserMapper.update(usedEntity, queryWrapper);
                }
            }

            // meeting_user_type 参会人员类型；值1为与会人员；2为负责人；3为班组安全员；4为创建人；

            // begin userType1参会人员，删除无效的数据
            UpdateWrapper<HseMeetingUser> delWrapperWithUserType1 = new UpdateWrapper<>();

            delWrapperWithUserType1.eq("meeting_info_id", meetingInfoId);
            delWrapperWithUserType1.eq("meeting_user_type", HseMeetingUser.MEETINGUSERTYPE_1_ATTENDEES);
            delWrapperWithUserType1.notIn("meeting_user", usedUserWithUserType1List);

            hseMeetingUserMapper.delete(delWrapperWithUserType1);
            // end userType1参会人员，删除无效的数据

            // begin userType2负责人，删除无效的数据
            UpdateWrapper<HseMeetingUser> delWrapperWithUserType2 = new UpdateWrapper<>();

            delWrapperWithUserType2.eq("meeting_info_id", meetingInfoId);
            delWrapperWithUserType2.eq("meeting_user_type", HseMeetingUser.MEETINGUSERTYPE_2_LEADING);
            delWrapperWithUserType2.notIn("meeting_user", usedUserWithUserType2List);

            hseMeetingUserMapper.delete(delWrapperWithUserType2);
            // end userType2负责人，删除无效的数据

            // begin userType3为班组安全员，删除无效的数据
            UpdateWrapper<HseMeetingUser> delWrapperWithUserType3 = new UpdateWrapper<>();

            delWrapperWithUserType3.eq("meeting_info_id", meetingInfoId);
            delWrapperWithUserType3.eq("meeting_user_type", HseMeetingUser.MEETINGUSERTYPE_3_TEAM_SAFETY);
            delWrapperWithUserType3.notIn("meeting_user", usedUserWithUserType3List);

            hseMeetingUserMapper.delete(delWrapperWithUserType3);
            // end userType3为班组安全员，删除无效的数据

            String strResultInfo = "保存" + saveRows + "行；修改" + updateRows + "行；";

            ajaxResult = AjaxResultUtil.createSuccessMessage(strResultInfo);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return ajaxResult;
    }

    @Override
    public <T extends HseMeetingUser> List<T> queryByMeetingInfoId(String reqMeetingInfoId) {
        if (StringUtil.isNullOrSpace(reqMeetingInfoId)) {
            return null;
        }

        QueryWrapper<HseMeetingUser> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("meeting_info_id", reqMeetingInfoId);

        return (List<T>) hseMeetingUserMapper.selectList(queryWrapper);
    }

    @Override
    public <T extends HseMeetingUser> List<T> queryByMeetingInfoIdShow(String reqMeetingInfoId) {
        if (StringUtil.isNullOrSpace(reqMeetingInfoId)) {
            return null;
        }

        HseMeetingUser usedHseMeetingUser = new HseMeetingUser();
        usedHseMeetingUser.setMeetingInfoId(reqMeetingInfoId);

        return (List<T>) hseMeetingUserMapper.loadByUserSingleShow(usedHseMeetingUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseMeetingUser> AjaxResult deleteById(List<String> reqMeetingInfoIdList) {
        final String logInfo = "[HseMeetingUser_deleteById_UUID_" + UUID.randomUUID() + "]";
        AjaxResult ajaxResult = null;

        try {
            if (ListUtil.getListSizeWith0(reqMeetingInfoIdList) <= 0) {
                return AjaxResultUtil.createErrorMessage("请求信息不正确", null);
            }

            LOGGER.info("{}reqMeetingInfoIdList:{};"
                    , logInfo
                    , reqMeetingInfoIdList
            );

            UpdateWrapper<HseMeetingUser> delWrapper = new UpdateWrapper<>();

            delWrapper.in("meeting_info_id", reqMeetingInfoIdList);

            int delRows = hseMeetingUserMapper.delete(delWrapper);

            ajaxResult = AjaxResultUtil.createSuccessMessage("删除成功", delRows);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return ajaxResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends HseMeetingUser> AjaxResult signIn(UserInfo loginUserInfo, Locale reqLocale, T reqEntity) {
        final String logInfo = "[HseMeetingUser_signIn_UUID_" + UUID.randomUUID() + "]";
        AjaxResult ajaxResult = null;

        try {
            String reqMeetingInfoId = reqEntity.getMeetingInfoId();
            String reqUserId = reqEntity.getUserID();

            LOGGER.info("{}printInfo;reqMeetingInfoId:{};reqUserId:{};"
                    , logInfo
                    , reqMeetingInfoId, reqUserId
            );

            if (StringUtil.hasNullOrSpace(reqMeetingInfoId, reqUserId)) {
                LOGGER.error("Check request parameter is fail");
                throw new ScpException("Check request parameter is fail");
            }

            Date nowDate = new Date();

//            // begin 获取登录用户的信息
//            String loginUserInfoUserId = loginUserInfo.getUserId();
//            String loginUserInfoUserName = loginUserInfo.getUserName();
//            // end 获取登录用户的信息

            HseMeetingUser usedEntity = null;
            int updateRows = 0;

            usedEntity = new HseMeetingUser();
            usedEntity.setMeetingSignIn(HseMeetingUser.MEETINGSIGNIN_1);
            usedEntity.setMeetingSignInTime(nowDate);

            UpdateWrapper<HseMeetingUser> updateWrapper = new UpdateWrapper<>();

            updateWrapper.eq("meeting_info_id", reqMeetingInfoId);
            updateWrapper.eq("meeting_sign_in", HseMeetingUser.MEETINGSIGNIN_0);
            updateWrapper.eq("meeting_user", reqUserId); // 使用请求的参数

            updateRows = hseMeetingUserMapper.update(usedEntity, updateWrapper);
            LOGGER.info("{}updateRows:{};", logInfo, updateRows);

            if (updateRows <= 0) {
                ajaxResult = AjaxResultUtil.createErrorMessage("签到失败，共签到" + updateRows + "次数。", null);
            } else {
                ajaxResult = AjaxResultUtil.createSuccessMessage("签到成功，共签到" + updateRows + "次数。");
            }
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return ajaxResult;
    }

    @Override
    public <T extends HseMeetingUser> List<T> queryNeedSendSms(int pageNum, int pageSize) {
        // 创建Page对象
        IPage<HseMeetingUser> queryPage = new Page<>();
        queryPage.setCurrent(pageNum);
        queryPage.setSize(pageSize);

        // 创建queryExample
        QueryWrapper<HseMeetingUser> queryWrapper = new QueryWrapper<>();

        queryWrapper.orderByDesc("meeting_info_id");

        queryWrapper.eq("sms_notice", HseMeetingUser.SMSNOTICE_1);
        queryWrapper.eq("sms_send_status", HseMeetingUser.SMSSENDSTATUS_0);

        IPage<HseMeetingUser> pageResult = hseMeetingUserMapper.selectPage(queryPage, queryWrapper);

        return (List<T>) pageResult.getRecords();
    }

    @Transactional
    @Override
    public <T extends HseMeetingUser> List<T> loadByMeetingInfoIdAndUserId(String hseMeetingInfoId, String meetingUserId) {
        if (StringUtil.hasNullOrSpace(hseMeetingInfoId, meetingUserId)) {
            return null;
        }

        QueryWrapper<HseMeetingUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("meeting_info_id", hseMeetingInfoId);
        queryWrapper.eq("meeting_user", meetingUserId);
        return (List<T>) hseMeetingUserMapper.selectList(queryWrapper);
    }

}
